﻿<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

	<head>
		<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
		<title>Application Services</title>
		<link type="text/css" rel="stylesheet" href="bootstrap.min.css" />
	</head>

	<body>
		<div class="document-contents">
			<p>
    Application Services are used to expose domain logic to the 
	presentation layer. An Application Service is called from presentation layer 
	with a DTO (Data Transfer Object) as parameter, uses domain objects to perform some 
	specific business logic and returns a DTO back to the presentation layer. 
	Thus, Presentation layer is completely isolated from Domain layer. In an 
	ideally layered application, presentation layer never directly works with 
	domain objects.</p>
			<h3 id="DocIApplicationServiceInterface">
    IApplicationService interface</h3>
			<p>
    In ASP.NET Boilerplate, an application service <strong>should</strong> implement 
				<strong>IApplicationService</strong> interface. It's good to create an 
				<strong>interface</strong> for each 
	Application Service. So, we first define an interface for an application 
	service as shown below:</p>
			<pre lang="cs">public interface IPersonAppService : IApplicationService
{
    void CreatePerson(CreatePersonInput input);
}</pre>
			<p>
				<strong>IPersonAppService</strong> has only one method. It's used by 
	presentation layer to create a new person.<strong> CreatePersonInput</strong> 
	is a DTO object as shown below:</p>
			<pre lang="cd">public class CreatePersonInput : IInputDto
{
    [Required]
    public string Name { get; set; }

    public string EmailAddress { get; set; }
}</pre>
			<p>Then we can implement the IPersonAppService:</p>
			<pre lang="cs">public class PersonAppService : IPersonAppService
{
    private readonly IRepository&lt;Person&gt; _personRepository;

    public PersonAppService(IRepository&lt;Person&gt; personRepository)
    {
        _personRepository = personRepository;
    }

    public void CreatePerson(CreatePersonInput input)
    {
        var person = _personRepository.FirstOrDefault(p =&gt; p.EmailAddress == input.EmailAddress);
        if (person != null)
        {
            throw new UserFriendlyException(&quot;There is already a person with given email address&quot;);
        }

        person = new Person { Name = input.Name, EmailAddress = input.EmailAddress };
        _personRepository.Insert(person);
    }
}</pre>
			<p>There are some important points here:</p>
			<ul>
				<li>PersonAppService uses 
					<a href="/Pages/Documents/Repositories#DocRepositoryImpl">IRepository&lt;Person&gt;</a> to perform 
	database operations. It uses <strong>constructor injection</strong> pattern. 
	We're using <a href="/Pages/Documents/Dependency-Injection">dependency 
	injection</a> here.</li>
				<li>PersonAppService implements <strong>IApplicationService</strong> (since 
	IPersonAppService extends IApplicationService), it's automatically 
	registered to Dependency Injection system by ASP.NET Boilerplate and can be 
	injected and used by other classes.</li>
				<li>
					<strong>CreatePerson</strong> method gets <strong>CreatePersonInput</strong>. 
	It's an input DTO and automatically validated by ASP.NET Boilerplate. See
					<a href="/Pages/Documents/Data-Transfer-Objects">DTO</a> and
					<a href="/Pages/Documents/Validating-Data-Transfer-Objects">validation</a> 
	documents for details.</li>
			</ul>
			<h4 id="DocAppServiceClass">ApplicationService class</h4>
			<p>An application service should implement IApplicationService interface. Also,
				<strong>optionally</strong>, can be derived from <strong>ApplicationService</strong> 
base class. Thus, IApplicationService is inherently implemented. Also, 
ApplicationService class has some base functionality that makes easy to <strong>logging</strong> 
and 
				<strong>localization</strong>. It's suggested to create a special base class for your application 
services that extends ApplicationService class. Thus, you can add some common 
functionality for all your application services. A sample application service 
class is shown below:</p>
			<pre lang="cs">public class TaskAppService : ApplicationService, ITaskAppService
{
    public TaskAppService()
    {
        LocalizationSourceName = &quot;SimpleTaskSystem&quot;;
    }

    public void CreateTask(CreateTaskInput input)
    {
        //Write some logs (Logger is defined in ApplicationService class)
        Logger.Info(&quot;Creating a new task with description: &quot; + input.Description);

        //Get a localized text (L is a shortcut for LocalizationHelper.GetString(...), defined in ApplicationService class)
        var text = L(&quot;SampleLocalizableTextKey&quot;);

        //TODO: Add new task to database...
    }
}</pre>
			<p>You can have a base class which defines LocalizationSourceName in it's 
constructor. Thus, you do not repeat it for all service classes. See
				<a href="/Pages/Documents/Logging">logging</a> and
				<a href="/Pages/Documents/Localization">localization</a> documents for more 
informations on this topics.</p>
			<h3 id="DocUsingUow">Unit of work</h3>
			<p>An application service method is a <strong>
					<a href="/Pages/Documents/Unit-Of-Work">unit of work</a>
				</strong> by default in 
ASP.NET Boilerplate.</p>
			<h4 id="DocUowTransactions">For connection &amp; transaction management</h4>
			<p>Say that we want to call two repository method in an application service 
method those must be transactional. Example:</p>
			<pre lang="cs">public void CreatePerson(CreatePersonInput input)
{
    var person = new Person { Name = input.Name, EmailAddress = input.EmailAddress };    
    _personRepository.Insert(person);
    _statisticsRepository.IncrementPeopleCount();
}</pre>
			<p>We inserted an item to People table, then incremented people count that is 
stored in another table field. These methods are implemented in different 
repositories but shares same connection and transaction. So, how?</p>

			<p>A database connection is opened and a transaction is started at the beginning 
of CreatePerson method by ASP.NET Boilerplate automatically. At the end of the 
method, the transaction is commited if no exception occurs and the connection is 
closed. Thus, all database operations in CreatePerson method is <strong>transactional</strong> 
(<strong>atomic</strong>) and rolled back if any exception is thrown. Thus, two repository methods in 
this example shares same connection and transaction.</p>
			<p>When you call
				<a href="/Pages/Documents/Repositories#DocGettingListOfEntities">
					<strong>GetAll()</strong>
				</a> 
method of a repository, it returns an IQueryable&lt;T&gt;. Database connection should 
be open after calling the repository method. This is because of deferred 
execution of IQueryable&lt;T&gt; and LINQ. Database query is actually performed when you call 
				<strong>ToList()</strong> method. See the example below:</p>
			<pre lang="cs">public SearchPeopleOutput SearchPeople(SearchPeopleInput input)
{
    //Get IQueryable&lt;Person&gt;
    var query = _personRepository.GetAll();

    //Add some filters if selected
    if (!string.IsNullOrEmpty(input.SearchedName))
    {
        query = query.Where(person =&gt; person.Name.StartsWith(input.SearchedName));
    }

    if (input.IsActive.HasValue)
    {
        query = query.Where(person =&gt; person.IsActive == input.IsActive.Value);
    }

    //Get paged result list
    var people = query.Skip(input.SkipCount).Take(input.MaxResultCount).ToList();

    return new SearchPeopleOutput {People = Mapper.Map&lt;List&lt;PersonDto&gt;&gt;(people)};
}</pre>
			<p>Since an application service method is a unit of work, database connection is 
open during the method execution. If you use GetAll() in a class that is not an 
application service, you should explicitly use
				<a href="/Pages/Documents/Unit-Of-Work">unit of work</a>.</p>
			<p>Note that I used AutoMapper library to convert List&lt;Person&gt; to 
List&lt;PersonDto&gt;. See
				<a href="/Pages/Documents/Data-Transfer-Objects#DocAutoMapping">DTO document</a> 
for details.</p>
			<h4 id="UowAutoSave">For automatically saving changes</h4>
			<p>For a unit of work method, ASP.NET Boilerplate saves 
all changes at the end of the method automatically. Assume that we need an 
application service method to update name of a person:</p>
			<pre lang="cs">public void UpdateName(UpdateNameInput input)
{
    var person = _personRepository.Get(input.PersonId);
    person.Name = input.NewName;
}</pre>
			<p>That's all, name was changed! We did not even called _personRepository.Update 
method. O/RM framework keep track of all changes of entities in a unit of work 
and reflects changes to the database.</p>
			<h4 id="DocUowMore">More</h4>
			<p>See <a href="/Pages/Documents/Unit-Of-Work">unit of work</a> documentation 
for more.</p>

			<h3 id="DocAppServiceLifecycle">Lifecycle of an application service</h3>
			<p>All application service instances are <strong>Transient</strong>. It means, they are 
instantiated per usage. ASP.NET Boilerplate strongly uses Dependency Injection 
technique. When an application service class needed to be injected, a new instance of the 
class is created automatically by dependency injection container. See
				<a href="/Pages/Documents/Dependency-Injection">Dependency Injection</a> 
documentation for more information.</p>
		</div>
	</body>

</html>
